#pragma once

#include <QObject>
#include <QAbstractSocket>
#include <QHostInfo>
#include <QTcpSocket>
#include <QByteArray>
#include <QTimer>
#include <QThread>
namespace infrastructure {
namespace io {

/**
 * @brief TCP客户端封装类
 * @details 继承QTcpSocket，提供自动重连、掉线检测等功能
 */
class TcpSocketClient : public QTcpSocket {
    Q_OBJECT

public:
    explicit TcpSocketClient(QObject *parent = nullptr);
    explicit TcpSocketClient(qintptr socketDescriptor, QObject *parent = nullptr);
    ~TcpSocketClient();

    /**
     * @brief 初始化连接
     * @param address 目标IP地址
     * @param port 目标端口
     * @return 是否成功
     */
    bool initConnection(const QHostAddress &address, quint16 port);

    /**
     * @brief 重置连接
     */
    void resetConnection(const QHostAddress& address, quint16 port);

    /**
     * @brief 重新连接
     */
    void reConnect();

signals:
    /**
     * @brief 断开连接信号
     * @note 此信号必须发出，线程管理类根据信号计数
     */
    void sig_sockDisConnect(qint64 socketDescriptor, const QString &ip, quint16 port, QThread *thread);

public slots:
    void tcpClientDisConnected();
    void disConTcp(qint64 socketDescriptor);

private slots:
    void slotConnected();
    void onErr(QAbstractSocket::SocketError error);

private:
    QHostAddress m_remoteIp;
    quint16 m_remotePort;
    qintptr socketID;
    QMetaObject::Connection dis;

    void onCheckState();
};

} // namespace io
} // namespace infrastructure
